package com.bilibili.service.impl;

import com.bilibili.entity.PicCartoon;
import com.bilibili.entity.PicPage;
import com.bilibili.exception.BusinessException;
import com.bilibili.mapper.PicCartoonMapper;
import com.bilibili.mapper.PicCategoryMapper;
import com.bilibili.mapper.PicPageMapper;
import com.bilibili.mapper.PicReadMapper;
import com.bilibili.service.PicPageService;
import com.bilibili.vo.PicUploadPageVo;
import com.bilibili.vo.PicUploadReadVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Service
public class PicPageServiceImpl implements PicPageService {

    @Autowired
    private PicPageMapper picPageMapper;

    @Autowired
    private PicCartoonMapper picCartoonMapper;

    @Autowired
    private PicReadMapper picReadMapper;

    @Override
    public Integer getPageCountByCartoonId(Integer cartoonId) {
        return picPageMapper.getPageCountByCartoonId(cartoonId);
    }


    @Override
    public List<PicPage> getPagesByCartoonId(Integer cartoonId) {
        List<PicPage> pagesByCartoonId = picPageMapper.getPagesByCartoonId(cartoonId);
        if (pagesByCartoonId.size() == 0) {
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画id不存在");
        }
        return pagesByCartoonId;
    }

    @Override
    public boolean addPage(PicUploadPageVo picUploadPageVo) {
        Integer cartoonId = picUploadPageVo.getCartoonId();
        String pageName = picUploadPageVo.getPageName();
        List<String> pages = picUploadPageVo.getPages();
        PicCartoon cartoonById = picCartoonMapper.getCartoonById(cartoonId);
        if (Objects.isNull(cartoonById)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "漫画id不存在");
        }
        if (StringUtils.isBlank(pageName)){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "章节名字不能为空");
        }
        if (Objects.isNull(pages)||pages.size()==0){
            throw new BusinessException(HttpStatus.BAD_REQUEST, "图片路径不能为空");
        }
        Integer maxPages = picPageMapper.getMaxPagesByCartoonId(cartoonId);
        //插入章节
        PicPage picPage = new PicPage();
        if (Objects.isNull(maxPages)||maxPages==0){
            //为了避免一开始没有章节的情况
            picPage.setNumber(1);
        }else {
            picPage.setNumber(maxPages+1);
        }
        picPage.setCartoonId(cartoonId);
        picPage.setPageName(pageName);
        picPageMapper.addPicPage(picPage);
        //插入每一页
        Integer pageId = picPage.getId();
        LinkedList<PicUploadReadVo> readVos = new LinkedList<>();
        for (String page : pages) {
            readVos.addLast(new PicUploadReadVo(page, pageId));
        }
        picReadMapper.addPicReads(readVos);
        return true;
    }


}
